package com.captainbank.tcl.tclapplication.utils;

import android.os.Build;

import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
//import android.util.Base64;
import java.util.Base64;

import javax.crypto.Cipher;

/**
 * Created by TCL on 2019/8/9.
 * Describe:
 */
public class RSAUtils {

    /**
     * 密钥长度 于原文长度对应 以及越长速度越慢
     */
    private final static int KEY_SIZE = 1024;
    private final static String publicKeyString = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdFesb/CC6KLDra6rbrmlKBKhDjnJog6XkYTGrmZlAQxzos4QPkqG5fnjWboY37rGEDnHG09lLTA94CWdCAxxKH9EBA5wB5cU1DN8LOEwG6PT1hgNK54FD7Kz7Lb2l+Xbut67DW0hXar/nXl9Tt9mraIbfEsdZ+idct83bmPhZzwIDAQAB";

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        if(!StringUtil.checkIsNotNull(publicKey)){
            publicKey = publicKeyString;
        }
        //base64编码的公钥
        byte[] decoded;
        //安卓api26以下无法使用java.util.Base64
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            decoded = Base64.getDecoder().decode(publicKey);
        }else{
            decoded = android.util.Base64.decode(publicKey,android.util.Base64.DEFAULT);
        }
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String cipherText;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            cipherText = Base64.getEncoder().encodeToString(cipher.doFinal(str.getBytes("UTF-8")));
        }else{
            cipherText = android.util.Base64.encodeToString(cipher.doFinal(str.getBytes("UTF-8")),android.util.Base64.DEFAULT);
        }
        return  cipherText;
    }

}
